// 两根线
// 同步：组件 commit -> mutations -> state
// 异步： 组件 dispatch -> actions -> commit -> mutations -> state
import { login, getInfo, getUserDetailById } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
export default {
  // 开启命名空间
  namespaced: true,
  // 放数据的地方
  state: {
    token: getToken() || null,
    userInfo: {}
  },
  // 相当于组件中计算属性
  getters: {},
  // 这个是唯一修改state中数据地方
  mutations: {
    // setCount(state) {}
    setToken(state, payload) {
      state.token = payload
      setToken(payload)
    },
    setUserInfo(state, payload) {
      state.userInfo = payload
    },
    removeToken(state) {
      state.token = null
      removeToken()
    },
    removeUserInfor(state) {
      state.userInfo = {}
    }
  },
  // 写异步的ajax的地方
  actions: {
    async login(store, payload) {
      // console.log(111)
      const token = await login(payload)
      // console.log(token)
      store.commit('setToken', token)
    },
    async getInfo(store) {
      const res = await getInfo()
      // console.log(res)
      const res1 = await getUserDetailById(res.userId)
      // console.log(res1)
      store.commit('setUserInfo', { ...res, ...res1 })
    },
    logout(store) {
      store.commit('removeToken')
      store.commit('removeUserInfor')
    }
    // store.commit()
    // getData(store){}
  }
}
